package com.dubito.room.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.dubito.room.dao.WordRoomDatabase
import com.dubito.room.entity.Word
import com.dubito.room.repository.WordRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * @author by liliang on 2020/6/17 11:08 AM
 */
class WordViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: WordRepository

    //使用LiveData和缓存getAlphabetizedWords返回的内容有几个好处：
    //-我们可以在数据上放置一个观察者（而不是轮询更改），并且只更新
    //数据实际更改时的UI。
    //-存储库通过ViewModel与UI完全分离。
    val allWords: LiveData<List<Word>>

    init {
        val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
        val dogDao = WordRoomDatabase.getDatabase(application, viewModelScope).dogDao()
        repository = WordRepository(wordsDao)
        allWords = repository.allWords
    }

    /**
     * 启动新的协同程序以非阻塞方式插入数据
     */
    fun insert(word: Word) = viewModelScope.launch(Dispatchers.IO) {
        repository.insert(word)
    }
}